<template>
  <div class="add_financing_page" v-loading="pageLoading">
    <!-- <div class="fail_mod" v-if="this.id">
      <img src="@/assets/icons/fail_status.png" alt="" class="icon">
      <div class="reason_box">
        <span class="reason">驳回原因：</span>
        <span class="text">企业信息与法人信息不一致，法人身份证附件</span>
      </div>
    </div> -->
    <div class="step_list">
      <div class="step_item">
        <img src="@/assets/production/jigouList/step_1.png" alt="" class="img">
        <div class="name">申请融资</div>
      </div>
      <img src="@/assets/production/jigouList/arrow_right.png" alt="" class="arrow_right" />
      <div class="step_item">
        <img src="@/assets/production/jigouList/step_2.png" alt="" class="img">
        <div class="name">平台审核</div>
      </div>
      <img src="@/assets/production/jigouList/arrow_right.png" alt="" class="arrow_right" />
      <div class="step_item">
        <img src="@/assets/production/jigouList/step_3.png" alt="" class="img">
        <div class="name">银行放贷</div>
      </div>
    </div>
    <el-form ref="form" :model="form" :rules="formRules" label-position="right" label-width="140px">
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">基础信息</h5>
          </div>
        </div>
        <div>
          <el-row class="row">
            <el-col :span="8">
              <el-form-item label="融资类型" prop="creditType">
                <el-select v-model="form.creditType" placeholder="请选择" style="width: 100%;">
                  <el-option
                    v-for="item in creditTypeList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="资金机构" prop="jigouName">
                <el-input v-model="form.jigouName" placeholder="请输入"></el-input>
                <!-- <el-select v-model="form.jigouName" placeholder="请选择" style="width: 100%;">
                  <el-option value="">请选择</el-option>
                  <el-option
                    v-for="item in financeList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                  >
                  </el-option>
                </el-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核心企业" prop="hexinName">
                <el-input v-model="form.hexinName" placeholder="请输入" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">融资信息</h5>
          </div>
        </div>
        <div>
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="融资金额(元)" prop="financingAmount" label-width="180px">
                <el-input v-model="form.financingAmount" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="综合融资利率(%)" prop="financingRate" label-width="180px">
                <el-input v-model="form.financingRate" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="融资期限" prop="month" label-width="180px">
                <el-select v-model="form.month" style="width: 100%;">
                  <el-option label="请选择" value=""></el-option>
                  <el-option
                    v-for="item in monthTypeList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="还款方式" prop="repaymentType" label-width="180px">
                <el-select v-model="form.repaymentType" style="width: 100%;">
                  <el-option label="请选择" value=""></el-option>
                  <el-option
                    v-for="item in repaymentTypeList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="预计放款金额（元）" prop="creditAvailableAmount" label-width="180px">
                <el-input v-model="form.creditAvailableAmount" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
    <div class="mod">
      <div class="title_box">
        <div class="title">
          <i class="icon"></i>
          <h5 class="name">贸易合同</h5>
        </div>
        <div class="tips">
          <div><span class="important">贸易合同</span>请上传PDF格式贸易合同文件</div>
          <el-form ref="contractForm" :model="contractForm" :rules="contractRules">
            <el-form-item prop="tradeContractInfo" label-width="0">
              <el-button type="primary" class="upload_btn" :loading="contractLoading">
                上传合同
                <input type="file" accept="application/pdf" class="upload_input" @change="uploadNewContract" />
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table :data="contractForm.tradeContractInfo" border>
        <el-table-column
          label="序号"
          type="index"
        >
        </el-table-column>
        <el-table-column
          v-for="(item, index) in contractColumns"
          :key="item.label"
          v-bind="item"
        >
          <template slot-scope="scope">
            <el-form ref="contractTableCell" :model="scope.row">
              <el-form-item
                v-if="item.type === 'date'"
                :prop="item.prop"
                label-width="0"
                style="margin-bottom: 20px;"
                :rules="tableCellRules(item.label, 'date')"
              >
                <el-date-picker
                  v-model="scope.row[item.prop]"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
              <el-form-item
                v-else
                :prop="item.prop"
                label-width="0"
                style="margin-bottom: 20px;"
                :rules="tableCellRules(item.label, 'input')"
              >
                <el-input  v-model="scope.row[item.prop]"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text">
              <a :href="baseURL + scope.row.url" target="_blank">预览</a>
            </el-button>
            <el-button type="text" @click="delContractRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-form ref="tradeForm" :model="tradeForm" :rules="tradeRules" label-position="right" label-width="140px">
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">贸易发票</h5>
          </div>
          <div class="tips">
            <div><span class="important">贸易发票</span>请上传JPG、PNG格式贸易发票文件</div>
            <el-form-item prop="tradeInvoiceInfo" label-width="0">
              <el-button type="primary" class="upload_btn" :loading="invoiceLoading">
                上传发票
                <input type="file" accept="image/jpg,image/png" class="upload_input" @change="ocrNewInvoice" />
              </el-button>
            </el-form-item>
          </div>
        </div>
        <el-table :data="tradeForm.tradeInvoiceInfo" border>
          <el-table-column
            v-for="item in invoiceColumns"
            :key="item.label"
            v-bind="item"
          >
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="previewBigImg(scope.row.url)">预览</el-button>
              <el-button type="text" @click="delInvoiceRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="total_box">
          共计发票金额：<span class="total">{{ tradeForm.invoiceTotalAmount }}</span>
        </div>
      </div>
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">收款银行账号</h5>
            <div class="desc">
              <i class="warn_icon el-icon-warning"></i>
              请按照银行要求使用制定企业回款（收款）账户信息
            </div>
          </div>
        </div>
        <div>
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="开户银行" prop="enterpriseBankId" label-width="160px">
                <el-select v-model="tradeForm.enterpriseBankId" @change="accountNameChange" style="width: 100%;">
                  <el-option label="请选择开户名称" value=""></el-option>
                  <el-option
                    v-for="item in bankAccountList"
                    :key="item.id"
                    :label="item.accountName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账号" label-width="160px">
                <el-input v-model="enterpriseBankObj.bankNumber" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="开户支行" label-width="160px">
                <el-input v-model="enterpriseBankObj.bankBranch" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="大额行号" label-width="160px">
                <el-input v-model="enterpriseBankObj.bankCode" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">其他资料</h5>
            <div class="desc">
              <i class="warn_icon el-icon-warning"></i>
              如果有相应资料或文件可以上传添加
            </div>
          </div>
          <div class="tips">
            <el-button type="primary" class="upload_btn" :loading="othersLoading">
              新增资料
              <input type="file" accept="image/jpg,image/png,application/pdf" class="upload_input" @change="uploadOthers" />
            </el-button>
          </div>
        </div>
        <el-table :data="tradeForm.otherInfo" border>
          <el-table-column label="序号" type="index" width="200px"></el-table-column>
          <el-table-column
            v-for="item in otherColumns"
            :key="item.label"
            :label="item.label"
            :proop="item.prop"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row[item.prop]"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text">
                <a :href="baseURL + scope.row.url" target="_blank">查看</a>
              </el-button>
              <el-button type="text" @click="delOtherRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">签署协议</h5>
          </div>
        </div>
        <div class="agreement_content">
          <el-form-item prop="agreement" label-width="0">
            <el-checkbox v-model="tradeForm.agreement">我已阅读并知晓同意 </el-checkbox>
            <span class="agreement">《企业授信协议》、</span>
            <span class="agreement">《企业账户锁定协议》</span>
          </el-form-item>
        </div>
      </div>
      <div class="mod">
        <div class="btns">
          <el-button class="btn btn_cancel" v-if="!this.id" :loading="saveLoading" @click="save">保 存</el-button>
          <el-button class="btn" type="primary" :loading="submitLoading" @click="submit">提 交</el-button>
        </div>
      </div>
    </el-form>
    <CustomDialog
      title="查看内容"
      width="70%"
      :visible="dialogVisible"
      @close="dialogVisible = false"
    >
      <div class="mask_dialog_content">
        <div class="img_box">
          <img :src="baseURL+ previewBigImgUrl" alt="" class="img" />
        </div>
      </div>
    </CustomDialog>
  </div>
</template>

<script>
import { getSaveFinancing, saveFinancing, addFinancing, financingDetail, uploadFile, ocrInvoice } from '@/api/production'
import { bankList } from '@/api/companyManage'
import CustomDialog from '@/customComponents/dialog'

export default {
  components: {
    CustomDialog,
  },
  data() {
    return {
      pageLoading: false,
      contractLoading: false,
      invoiceLoading: false,
      othersLoading: false,
      saveLoading: false,
      submitLoading: false,
      creditTypeList: [], // 授信类型列表
      financeList: [], // 资金机构列表
      monthTypeList: [], // 还款期限列表
      repaymentTypeList: [], // 还款方式列表
      bankAccountList: [], // 银行账户列表
      contractColumns: [], // 贸易合同列
      invoiceColumns: [], // 贸易发票列
      otherColumns: [], // 其他资料列
      id: '', // 授信id
      detailObj: {}, // 授信详情信息
      projectStatusList: [], // 项目状态列表
      form: {
        financingConfigId: '', // 融资配置表id
        creditType: '', // 授信类型
        jigouName: '', // 资金机构名称
        hexinName: '', // 核心企业名称
        financingAmount: '', // 申请融资金额（元）
        financingRate: '', // 融资利率（%）
        month: '', // 融资期限
        repaymentType: '', // 还款方式字典（repayment_type）
        creditAvailableAmount: '', // 可用授信（元）
      },
      formRules: {
        creditType: [{ required: true, trigger: ['change', 'blur'], message: '请选择授信类型' }], // 授信类型
        jigouName: [{ required: true, trigger: ['change', 'blur'], message: '请选择资金机构' }], // 资金机构
        hexinName: [{ required: true, trigger: ['change', 'blur'], message: '请选择核心企业' }], // 核心企业
        financingAmount: [{ required: true, trigger: ['change', 'blur'], message: '请输入申请融资金额' }], // 申请融资金额（元）
        financingRate: [{ required: true, trigger: ['change', 'blur'], message: '请输入融资利率' }], // 融资利率（%）
        month: [{ required: true, trigger: ['change', 'blur'], message: '请选择融资期限' }], // 融资期限
        repaymentType: [{ required: true, trigger: ['change', 'blur'], message: '请选择还款方式字典' }], // 还款方式字典（repayment_type）
        creditAvailableAmount: [{ required: true, trigger: ['change', 'blur'], message: '请输入可用授信' }], // 可用授信（元）
      },
      contractForm: {
        tradeContractInfo: [], // 贸易合同json
      },
      contractRules: {
        tradeContractInfo: [
          {
            validator: (rule, cellValue, callback) => {
              if (cellValue?.length) {
                callback()
              } else {
                callback('请上传贸易合同')
              }
            },
          }
        ], // 贸易合同json
      },
      tradeForm: {
        tradeInvoiceInfo: [], // 贸易发票json
        invoiceTotalAmount: 0, // 发票总金额
        enterpriseBankId: '', // 银行账户id
        otherInfo: [], // 其他资料
        agreement: false, // 签署协议
      },
      tradeRules: {
        tradeInvoiceInfo: [
          {
            validator: (rule, cellValue, callback) => {
              if (cellValue?.length) {
                callback()
              } else {
                callback('请上传发票')
              }
            },
          }
        ], // 贸易发票json
        enterpriseBankId: [
          { required: true, trigger: ['change', 'blur'], message: '请选择开户名称' },
          { validator: (rule, cellValue, callback) => {
              if (cellValue) {
                callback()
              } else {
                callback('请选择开户名称')
              }
            },
            trigger: ['change']
          },
        ], // 银行账户id
        agreement: [
          {
            validator: (rule, cellValue, callback) => {
              if (cellValue) {
                callback()
              } else {
                callback('请勾选协议')
              }
            },
            trigger: ['change', 'blur'],
          }
        ], // 签署协议
      },
      enterpriseBankObj: {
        bankNumber: '',
        bankBranch: '',
        bankCode: '',
      }, // 银行信息
      baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :
        process.env.VUE_APP_HTTP_REQUEST_ADDRESS,
      dialogVisible: false, // 预览图弹窗
      previewBigImgUrl: '', // 预览图

    }
  },
  created() {
    this.contractColumns = [
      {
        label: '合同名称',
        prop: 'contractName'
      },
      {
        label: '合同编号',
        prop: 'contractCode'
      },
      {
        label: '合同金额(元)',
        prop: 'contractAmount'
      },
      {
        label: '合同签订日期',
        prop: 'contractDateStart',
        type: 'date',
      },
      {
        label: '合同结束日期',
        prop: 'contractDateEnd',
        type: 'date',
      },
    ]
    this.invoiceColumns = [
      {
        label: '序号',
        type: 'index',
      },
      {
        label: '发票类型',
        prop: 'invoiceTypeDesc'
      },
      {
        label: '发票代码',
        prop: 'code'
      },
      {
        label: '发票号码',
        prop: 'no'
      },
      {
        label: '发票金额(元)',
        prop: 'sumAmount'
      },
      {
        label: '开票日期',
        prop: 'date'
      },
      {
        label: '购买方',
        prop: 'buyerName'
      },
      {
        label: '销售方',
        prop: 'sellerName'
      },
    ]
    this.otherColumns = [
      {
        label: '文件名称',
        prop: 'fileName'
      },
    ]
  },
  watch: {
    'tradeForm.tradeInvoiceInfo': {
      handler: function(newVal, oldVal) {
        this.tradeForm.invoiceTotalAmount = newVal.reduce((res, value) => {
          return res+= value.sumAmount
        }, 0)
      },
      deep: true,
    }
  },
  mounted() {
    if (this.$route?.query?.financingConfigId) {
      this.form.financingConfigId = this.$route.query.financingConfigId
    }
    if (this.$route.query.jigouName) {
      this.form.jigouName = this.$route.query.jigouName
    }
    if (this.$route?.query?.hexinName) {
      this.form.hexinName = this.$route.query.hexinName
    }
    Promise.all([
      this.getCreditType(),
      this.getFinanceList(),
      this.getMonthTypeList(),
      this.getRepaymentTypeList(),
      this.getBankAccountList(),
    ]).then(() => {
      if (this.$route.query?.id) {
        this.id = this.$route.query.id
      }
      this.getFinancingDetail()
    })
  },
  methods: {
    // 获取授信类型
    getCreditType() {
      return new Promise((resolve, reject) => {
        this.getDicts('credit').then((res) => {
          if (res.code === 200) {
            this.creditTypeList = res.data
            resolve()
          } else {
            reject()
          }
        }).catch(() => {
          reject()
        })
      })
    },
    // 获取资金机构列表
    getFinanceList() {
      return new Promise((resolve, reject) => {
        this.getDicts('finance').then((res) => {
          if (res.code === 200 ) {
            this.financeList = res.data
            resolve()
          } else {
            reject()
          }
        }).catch(() => {
          reject()
        })
      })
    },
    // 获取融资期限列表
    getMonthTypeList() {
      return new Promise((resolve, reject) => {
        this.getDicts('month_type').then((res) => {
          if ( res.code === 200) {
            this.monthTypeList = res.data
            resolve()
          } else {
            reject()
          }
        }).catch(() => {
          reject()
        })
      })
    },
    // 获取还款方式列表
    getRepaymentTypeList() {
      return new Promise((resolve, reject) => {
        this.getDicts('repayment_type').then((res) => {
          if ( res.code === 200) {
            this.repaymentTypeList = res.data
            resolve()
          } else {
            reject()
          }
        }).catch(() => {
          reject()
        })
      })
    },
    // 获取用户银行账户列表
    getBankAccountList() {
      return new Promise((resolve, reject) => {
        bankList().then((res) => {
          if (res.code === 200) {
            this.bankAccountList = res.rows
            resolve()
          } else {
            reject()
          }
        }).catch(() => {
          reject()
        })
      })
    },
    // 获取详情数据返显
    getFinancingDetail() {
      // this.detailObj = JSON.parse('{"financingConfigId":"1","creditType":"20","jigouName":"工商银行","hexinId":"","hexinName":"核心企业有限公司","financingAmount":"9000","financingRate":"12","month":"36个月","repaymentType":"长期付息到期还本","creditAvailableAmount":"7000","tradeContractInfo":"[{\\"contractName\\":\\"合同1\\",\\"contractCode\\":\\"0000\\",\\"contractAmount\\":\\"900\\",\\"contractDateStart\\":\\"2025-03-04\\",\\"contractDateEnd\\":\\"2025-03-28\\",\\"url\\":\\"/profile/upload/2025/03/01/贸易合同_20250301162244A206.pdf\\"}]","tradeInvoiceInfo":"[{\\"type\\":\\"20101\\",\\"invoiceTypeDesc\\":\\"山东增值税专用发票\\",\\"code\\":\\"3700174130\\",\\"no\\":\\"07758015\\",\\"checkAmount\\":70137.06,\\"date\\":\\"20181004\\",\\"sumAmount\\":81359,\\"pretaxAmount\\":70137.06,\\"buyerName\\":\\"香河万利通实业有限公司\\",\\"buyerBank\\":\\"工行廊坊和平支行0410002619300048085\\",\\"sellerName\\":\\"招远市江龙石材有限公司\\",\\"sellerBank\\":\\"招远市农村信用合作联社宋家信用社90606491020100023394\\",\\"check\\":true,\\"vcode\\":\\"\\",\\"typeDesc\\":\\"增值税专用发票\\",\\"url\\":\\"/profile/upload/2025/03/01/发票1_20250301162250A207.jpg\\"}]","invoiceTotalAmount":81359,"enterpriseBankId":33,"otherInfo":"[{\\"fileName\\":\\"文件\\",\\"url\\":\\"/profile/upload/2025/03/01/发票3_20250301162301A208.jpg\\"}]"}')
      let result
      if (this.id) {
        result = financingDetail(this.id)
      } else {
        result = getSaveFinancing()
      }
      result.then((res) => {
        this.pageLoading = false
        this.detailObj = res.data
        Object.keys(this.form).forEach((key) => {
          this.form[key] = this.detailObj[key]
        })
        this.contractForm.tradeContractInfo = JSON.parse(this.detailObj?.tradeContractInfo || '[]')
        this.tradeForm.tradeInvoiceInfo = JSON.parse(this.detailObj.tradeInvoiceInfo)
        this.tradeForm.invoiceTotalAmount = this.detailObj.invoiceTotalAmount
        this.tradeForm.enterpriseBankId = this.detailObj.enterpriseBankId
        this.accountNameChange(this.detailObj.enterpriseBankId)
        this.tradeForm.otherInfo = JSON.parse(this.detailObj.otherInfo)
      }).catch(() => {
        this.pageLoading = false
      })
    },
    // 开户银行change
    accountNameChange(value) {
      const item = this.bankAccountList.find((item) => {
        if (item.id === value) {
          return item
        }
      })
      if (item) {
        this.enterpriseBankObj = { ...this.enterpriseBankObj, ...item }
      }
    },
    // 上传贸易合同
    uploadNewContract(e) {
      const file = e.target.files[0]
      e.target.value = ''
      this.contractLoading = true
      uploadFile({ file }).then((res) => {
        this.contractLoading = false
        this.contractForm.tradeContractInfo = [
          ...this.contractForm.tradeContractInfo,
          {
            contractName: '',
            contractCode: '',
            contractAmount: '',
            contractDateStart: '',
            contractDateEnd: '',
            url: res.fileName,
          }
        ]
      }).catch(() => {
        this.contractLoading = false
      })
    },
    // 删除贸易合同
    delContractRow(index) {
      this.contractForm.tradeContractInfo.splice(index, 0)
      this.$forceUpdate()
    },
    // 最新贸易发票ocr
    ocrNewInvoice(e) {
      this.invoiceLoading = true
      const file = e.target.files[0]
      e.target.value = ''
      ocrInvoice({ file }).then((res) => {
        this.invoiceLoading = false
        if (res.code === 200) {
          this.tradeForm.tradeInvoiceInfo = [...this.tradeForm.tradeInvoiceInfo, { ...res.data.invoice, url: res.data.url }]
        }
      }).catch(() => {
        this.invoiceLoading = false
      })
    },
    // 删除贸易发票
    delInvoiceRow(index) {
      this.tradeForm.tradeInvoiceInfo.splice(index, 1)
      this.$forceUpdate()
    },
    // 上传其他资料
    uploadOthers(e) {
      this.othersLoading = true
      const file = e.target.files[0]
      e.target.value = ''
      uploadFile({ file }).then((res) => {
        this.othersLoading = false
        this.tradeForm.otherInfo = [
          ...this.tradeForm.otherInfo,
          {
            fileName: '',
            url: res.fileName,
          },
        ]
      }).catch(() => {
        this.othersLoading = false
      })
    },
    // 删除其他资料
    delOtherRow(index) {
      this.tradeForm.otherInfo.splice(index, 1)
      this.$forceUpdate()
    },
    // 预览发票大图
    previewBigImg(url) {
      this.previewBigImgUrl = url
      this.dialogVisible = true
    },
    // save
    save() {
      const { agreement, ...rest } = this.tradeForm
      const data = {
        ...this.form,
        tradeContractInfo: JSON.stringify(this.contractForm.tradeContractInfo),
        ...rest,
        tradeInvoiceInfo: JSON.stringify(this.tradeForm.tradeInvoiceInfo),
        otherInfo: JSON.stringify(this.tradeForm.otherInfo)
      }
      console.log(data)
      this.saveLoading = true
      saveFinancing(data).then(() => {
        this.saveLoading = false
        this.$message({
          type: 'success',
          message: '保存成功'
        })
      }).catch(() => {
        this.saveLoading = false
        this.$message({
          type: 'error',
          message: '保存失败'
        })
      })
    },
    // 表格中的输入校验规则
    tableCellRules(label, type) {
      const rules = {
        required: true,
        trigger: ['change', 'blur'],
        message: `${type === 'date' ? '请选择' : '请输入'}${label}`
      }
      return rules
    },
    // $refs.form 校验
    formValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject('form')
          }
        })
      })
    },
    // $refs.contractForm 校验
    contractFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.contractForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject('contractForm')
          }
        })
      })
    },
    // $ref.contractTableCell 校验，合同表格中的校验
    contractTableCellValidate() {
      console.log(this.$refs.contractTableCell)
      const pList = []
      if (this.$refs?.contractTableCell?.length) {
        this.$refs.contractTableCell.forEach((ref) => {
          pList.push(new Promise((resolve, reject) => {
            ref.validate((valid) => {
              if (valid) {
                resolve()
              } else {
                reject('cell')
              }
            })
          }))
        })
      }
      return pList
    },
    // $refs.tradeForm 校验
    tradeFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.tradeForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject('tradeForm')
          }
        })
      })
    },
    submit() {
      const { agreement, ...rest } = this.tradeForm
      const data = {
        ...this.form,
        tradeContractInfo: JSON.stringify(this.contractForm.tradeContractInfo),
        ...rest,
        tradeInvoiceInfo: JSON.stringify(this.tradeForm.tradeInvoiceInfo),
        otherInfo: JSON.stringify(this.tradeForm.otherInfo)
      }
      console.log(data)
      console.log(JSON.stringify(data))
      this.submitLoading = true
      Promise.all([
        this.formValidate(),
        this.contractFormValidate(),
        this.tradeFormValidate(),
        ...this.contractTableCellValidate(),
      ]).then((res) => {
        addFinancing(data).then((res) => {
          this.submitLoading = false
          this.$message({
            type: 'success',
            message: '提交成功',
            onClose: () => {
              this.$router.back()
            }
          })
        }).catch(() => {
          this.submitLoading = false
        })
      }).catch((error) => {
        this.loading = false
        this.$message({
          type: 'error',
          message: '有信息未填',
          duration: 3000,
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';

.add_financing_page {
  .fail_mod {
    border: 1px solid #FF4D4F;
    border-radius: 12px;
    padding: 26px 30px;
    background-color: #FFF7F6;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    .icon {
      display: block;
      width: 48px;
      height: 48px;
      margin-right: 10px;
    }
    .reason_box {
      color: #FF4D4F;
      font-weight: 600;
      .reason {
        font-size: 20px;
        margin-right: 8px;
      }
      .text {
        font-size: 14px;
      }
    }
  }
  .step_list {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
    background: linear-gradient(to bottom, #DFEFFF, #FFFFFF);
    box-shadow: 0 2px 6px 0 rgba(1, 24, 70, 0.10);
    border-radius: 6px;
    margin-bottom: 16px;
    .step_item {
      .img {
        display: block;
        width: 140px;
        height: 140px;
      }
      .name {
        color: $theme;
        font-size: 22px;
        text-align: center;
      }
    }
    .arrow_right {
      display: block;
      width: 170px;
      height: 78px;
      margin: 0 100px;
    }
  }
  .mod {
    background-color: #fff;
    box-shadow: 0 1px 2px 0 rgba(1, 24, 70, 0.09);
    border-radius: 6px;
    margin-bottom: 16px;
    padding: 20px 16px 24px;
    .title_box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      .title {
        display: flex;
        align-items: center;
        .icon {
          width: 3px;
          height: 16px;
          border-radius: 1px;
          background-color: $theme;
          margin-right: 5px;
        }
        .name {
          color: #333;
          font-size: 16px;
          font-weight: 600;
        }
        .desc {
          margin-left: 20px;
          color: #F29C1C;
          font-size: 13px;
          .warn_icon {
            font-size: 14px;
            margin-right: 8px;
          }
        }
      }
      .tips {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #777;
        font-size: 14px;
        .important {
          color: $theme;
          margin-right: 4px;
        }
        .upload_btn {
          position: relative;
          margin-left: 24px;
          .upload_input {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 2;
            opacity: 0;
            cursor: pointer;
          }
        }
      }
    }
    ::v-deep .el-form-item {
      margin-bottom: 0;
    }
    ::v-deep .el-form-item--medium .el-form-item__label {
      color: #777;
    }
    .row {
      margin-bottom: 20px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .total_box {
      height: 32px;
      line-height: 32px;
      background-color: #FFFAF4;
      color: #333;
      font-size: 14px;
      font-weight: 500;
      border-radius: 2px;
      padding-left: 28px;
      margin-top: 20px;
      .total {
        color: #FF4D4F;
        font-size: 20px;
      }
    }
    .agreement_content {
      padding: 20px 24px 16px;
      font-size: 14px;
      .agreement {
        color: $theme;
      }
    }
    .btns {
      display: flex;
      justify-content: center;
      align-items: center;
      .btn {
        width: 120px;
      }
      .btn_cancel {
        margin-right: 24px;
      }
    }
  }
}
</style>
